/*
Tencent is pleased to support the open source community by making vConsole available.

Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.

Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://opensource.org/licenses/MIT

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

/**
 * A Front-End Console Panel for Mobile Webpage
 */

// global
import './lib/symbol.js';

// classes
import Core from './core/core.js';

class TVConsole extends Core {
  constructor(options = {
    defaultPlugins: ['system'],
    maxLogNumber: 100       //默认设置为100条
  }) {
    super(options);
    this._currentKeys = "";
    this._onkeydownTimer = null;
    this.delay = options.delay || 600;  //按键延迟
    this.keyMap = options.keyMap || {
      "1": {type: "tabbar", name: "default"},
      "11": {type: "topbar", name: "all"}, "12": {type: "topbar", name: "log"}, "13": {type: "topbar", name: "info"}, "14": {type: "topbar", name: "warn"}, "15": {type: "topbar", name: "error"},
      "2": {type: "tabbar", name: "system"},
      "21": {type: "topbar", name: "all"}, "22": {type: "topbar", name: "log"}, "23": {type: "topbar", name: "info"}, "24": {type: "topbar", name: "warn"}, "25": {type: "topbar", name: "error"},
      
    };
  }
  _keycodeToKey(keycode) {
    return {
      "48": "0", "49": "1", "50": "2", "51": "3", "52": "4", "53": "5", "54": "6", "55": "7", "56": "8", "57": "9", //电脑
      "32": "space",  //电脑
      "105": "#",     //遥控器
      "106": "*",     //遥控器
      "40": "﹀",      //遥控器  上按键
      "38": "︿",      //遥控器  下按键
    }[keycode];
  }
  _doKeydownEvent() {
    if (this._currentKeys === "") return;
    const tabbar = this.keyMap[this._currentKeys];
    switch(this._currentKeys) {
      case "#":   //隐藏
      case "space": 
        setTimeout(_ => {
          this.resumeOnKeyEvent();  //还原按键事件
        }, this.delay)
        this.hide();
        break;
      case "0":   //清除控制台
        if (this.tool.isFunction(this.pluginList[x.activedTab].clearLog)) {
          this.pluginList[x.activedTab].clearLog();
          this.triggerEvent('clearLog');
        }
        break;
      case "*":   //展开对象
        this.openFold();
        break;
      case "**":  //关闭对象
        this.closeFold();
        break;
      default: 
        if (!tabbar) break;
        //切换
        if (tabbar.type === "tabbar") {
          //切换tabbar
          this.showTab(tabbar.name);
        } else if (tabbar.type === "topbar") {
          //切换topbar
          this.showTopbar(tabbar.name);
        }
    }
    this._currentKeys = "";
  }
  isShow() {
    return this.$.one('.vc-panel', this.$dom).style.display === 'block';
  }
  show() {
    this.removeOnKeyEvent();
    this.registerOnKeyEvent();
    super.show();
  }
  showTopbar(topbarId) {
    if (!this.isInited) {
      return;
    }
    this.$.removeClass(this.$.all('.vc-topbar-' + this.activedTab, this.$dom), 'vc-actived');
    this.$.addClass(this.$.one('#__vc_topbar_' + this.activedTab + "_" + topbarId), 'vc-actived');
    this.pluginList[this.activedTab].showLogType(topbarId);
  }
  /**
   * 展开Fold  没有展开的是没有v-toggle的class的
   */
  openFold() {
    this.$.all(".vc-fold-outer").forEach(item => {
      // IE浏览器
      if(document.all && !this.$.hasClass(item, "vc-toggle")) {
        item.click();
      }
      // 其它浏览器
      else if (!this.$.hasClass(item, "vc-toggle")) {
          var e = document.createEvent("MouseEvents");
          e.initEvent("click", true, true);
          item.dispatchEvent(e);
      }
    })
  }
  /**
   * 关闭展开的Fold，展开的Fold存在vc-toggle的class
   */
  closeFold() {
    this.$.all(".vc-fold-outer").forEach(item => {
      // IE浏览器
      if(document.all && this.$.hasClass(item, "vc-toggle")) {
        item.click();
      }
      // 其它浏览器
      else if (this.$.hasClass(item, "vc-toggle")) {
          var e = document.createEvent("MouseEvents");
          e.initEvent("click", true, true);
          item.dispatchEvent(e);
      }
    })
  }
  registerOnKeyEvent() {
    const that = this;
    window.document.onkeydown = function (event) {
      event = event || window.event;
      that._onkeydownTimer && clearTimeout(that._onkeydownTimer);
      that._currentKeys += that._keycodeToKey(event.keyCode) + "";
      that.$.one("#vc_show_key_box").innerText = that._currentKeys;
      that._onkeydownTimer = setTimeout(_ => {
        that._doKeydownEvent();
        that.$.one("#vc_show_key_box").innerText = "";
      }, 1000);
    }
  }
  removeOnKeyEvent() {
    this.oldOnKeydown = window.document.onkeydown;
    this.oldOnKeypress = window.document.onkeypress;
    this.oldOnKeyup = window.document.onkeyup;
    window.document.onkeydown = window.document.onkeyup = window.document.onkeypress = null;
    if (window.top && window.top !== window) {
      this.oldOnKeydownTop = top.document.onkeydown;
      this.oldOnKeypressTop = top.document.onkeypress;
      this.oldOnKeyupTop = top.document.onkeyup;
      top.document.onkeydown = top.document.onkeyup = top.document.onkeypress = null;
    }
  }
  resumeOnKeyEvent() {
    window.document.onkeydown = this.oldOnKeydown;
    window.document.onkeypress = this.oldOnKeypress;
    window.document.onkeyup = this.oldOnKeyup;
    if (window.top && window.top !== window) {
      top.document.onkeydown = this.oldOnKeydownTop;
      top.document.onkeypress = this.oldOnKeypressTop;
      top.document.onkeyup = this.oldOnKeyupTop;
    }
  }
}

// export
export default TVConsole;